import {LOGIN,ON_LOGINING,LOGIN_SUCCESS,LOGIN_FAIL,VALIDATE_ERROR} from '../actionTypes'
import {login} from '../api'
import {loginValidate} from '../validator/login'
import Validator from '../validator/index'
import loginValidator from '../validator/login'
export function validateError (err) {
    return {
        type : VALIDATE_ERROR,
        error: err
    }
}

export function onLoading  (loginInfo) {
    return {
        type: ON_LOGINING,
        loginInfo
    }
}
export function loginSuccess  (loginInfo, json)  {
    return {
        type: LOGIN_SUCCESS,
        loginInfo,
        json
    }
}
export function loginFail  (error)  {
    return {
        type: LOGIN_FAIL,
        error: error
    }

}

export function loginAction  (loginInfo){
    return async (dispatch, getState) => {
        let state = getState()
        if(state.isloading !== undefined && state.isloading) {
            return
        }
        let validator = new Validator(loginValidator)
        let res = await validator.scene('login').check(loginInfo)
        if(res !== true) {
            return dispatch(validateError(res))
        }
        dispatch(onLoading(loginInfo))
        fetch(login,{
            method: 'POST',
            body:JSON.stringify(loginInfo),
        }).then(response => response.json())
            .then(json => {
                if(json.code === 0 || json.code === '0') {
                    dispatch(loginSuccess(loginInfo,json))
                    setTimeout(()=>{
                        window.location.href = json.url?json.url:'/ucenter'
                    },1000)
                }else {
                    dispatch(loginFail(json.msg))
                }
            }).catch(err => {
                dispatch(loginFail(err))
        })

    }
}